import { HttpException, Injectable } from '@nestjs/common';
import { AuthDto } from './dto/auth.dto';
import { User } from 'src/user/entities/user.entity';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';

const TOKEN_SECRET = process.env.TOKEN_SECRET;

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  /** 生成token */
  private generateToken({ id }: User) {
    return {
      token: this.jwtService.sign(
        {
          id,
        },
        { secret: TOKEN_SECRET },
      ),
    };
  }

  async signup(authDto: AuthDto) {
    let user = await User.findOneBy({ username: authDto.username });

    if (user == null) {
      throw new HttpException('用户不存在', 201);
    }
    if (await argon2.verify(user.password, authDto.password)) {
      let token = this.generateToken(user);
      return token;
    }

    throw new HttpException('账号密码不一致', 201);
  }
}
